package com.example.lexiangbackend.repository;

import com.example.lexiangbackend.entity.PlayHistory;
import com.example.lexiangbackend.entity.Music;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface PlayHistoryRepository extends JpaRepository<PlayHistory, Long> {
    
    /**
     * 根据用户ID查找播放历史
     */
    Page<PlayHistory> findByUserUserIdOrderByPlayTimeDesc(Long userId, Pageable pageable);
    
    /**
     * 获取用户播放过的音乐列表（去重）
     */
    @Query("SELECT DISTINCT h.music FROM PlayHistory h WHERE h.user.userId = :userId ORDER BY h.playTime DESC")
    Page<Music> findDistinctMusicByUserId(@Param("userId") Long userId, Pageable pageable);
    
    /**
     * 统计用户播放次数
     */
    long countByUserUserId(Long userId);
    
    /**
     * 统计音乐播放次数
     */
    long countByMusicMusicId(Long musicId);
    
    /**
     * 获取用户最近播放的音乐
     */
    @Query("SELECT h.music FROM PlayHistory h WHERE h.user.userId = :userId ORDER BY h.playTime DESC")
    Page<Music> findRecentMusicByUserId(@Param("userId") Long userId, Pageable pageable);
} 